package com.hktf.moedokilock.activity;

import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hktf.corelib.eventBus.WxPayEvent;
import com.hktf.corelib.jsonbean.Goods;
import com.hktf.corelib.jsonbean.UserDto;
import com.hktf.corelib.jsonbean.WXPayParams;
import com.hktf.corelib.jsonbean.response.GetGoodsResult;
import com.hktf.corelib.jsonbean.response.GetWxAppPayParamsResult;
import com.hktf.corelib.jsonbean.response.LoginResult;
import com.hktf.corelib.utils.CommUtils;
import com.hktf.corelib.utils.GsonUtils;
import com.hktf.corelib.utils.UIUtils;
import com.hktf.moedokilock.R;
import com.hktf.moedokilock.adapter.GoodsAdapter;
import com.hktf.uilib.activity.ProtocolWebViewActivity;
import com.hktf.uilib.app.BaseActivity;
import com.hktf.uilib.callback.BaseCallBackNew;
import com.hktf.uilib.engine.DriverEngine;
import com.hktf.uilib.utils.DlgUtils;
import com.hktf.uilib.utils.WxsdkUtil;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

public class VipPayActivity extends BaseActivity implements
        OnClickListener {


    private RelativeLayout rlStep1;
    private TextView tvPay;
    private androidx.recyclerview.widget.RecyclerView recyclerView;
    private android.widget.FrameLayout flCb;
    private android.widget.CheckBox cb;
    private TextView tvProtocol;
    private RelativeLayout rlPay;

    @Override
    public int getLayoutResID() {
        return R.layout.act_vip_pay;
    }


    @Override
    public void initListener() {

    }
    private Goods checkedGoods;

    @Override
    public void initData() {

        showLoadingGet();
        DriverEngine.goodsList(new BaseCallBackNew<GetGoodsResult>(GetGoodsResult.class){
            @Override
            public void onSUCCESS(Response<GetGoodsResult> response) {
                DlgUtils.disMissDlg();
                GetGoodsResult body = response.body();
                List<Goods> data = body.getData();
                data.get(0).setChecked(true);
                goodsAdapter.setNewData(data);
                checkedGoods=data.get(0);
                refreshTvBtn();
            }
        });


    }

    private void refreshTvBtn(){
        tvPay.setText(getString(com.hktf.uilib.R.string.vip_open)+checkedGoods.getName());
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        CommUtils.closeInput(v);
    }


    public void onDestroy() {
        super.onDestroy();
        try {
            rlStep1.clearAnimation();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private GoodsAdapter goodsAdapter;



    public void initView() {
        setFlag();
//        setTitle(UIUtils.getString(R.string.vip_title));
        setBackClick();

        rlStep1=findViewById(R.id.rl_step1);
        UIUtils.startScal(rlStep1);
        tvPay = findViewById(R.id.tv_pay);
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(goodsAdapter = new GoodsAdapter(new ArrayList<>()));
        goodsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                for (Goods datum : goodsAdapter.getData()) {
                    datum.setChecked(false);
                }
                Goods item = goodsAdapter.getItem(i);
                checkedGoods=item;
                item.setChecked(true);
                goodsAdapter.notifyDataSetChanged();
                refreshTvBtn();
            }
        });
        flCb = findViewById(R.id.fl_cb);
        cb = findViewById(R.id.cb);
        tvProtocol = findViewById(R.id.tv_protocol);
        tvProtocol.setOnClickListener(v -> {
            Intent intent = new Intent(VipPayActivity.this, ProtocolWebViewActivity.class);
            intent.putExtra("flag", 2);
            startActivity(intent);
        });

        tvPay.setOnClickListener(v -> {
            pay();
        });
    }
    private void pay(){
        if (checkedGoods == null) {
            return;
        }
        showLoadingGet();
//        WsRequest wsRequest=new WsRequest();
//        wsRequest.setRequestCode(WebsocketConstants.WX_PAY);
//        wsRequest.setGid(checkedGoods.getId());
//        WebSocketSingleton.getInstance().sendMessage(GsonUtils.createGsonString(wsRequest));

        DriverEngine.getWxPayParams(checkedGoods.getId(),new BaseCallBackNew<GetWxAppPayParamsResult>(GetWxAppPayParamsResult.class){
            @Override
            public void onSUCCESS(Response<GetWxAppPayParamsResult> response) {
                DlgUtils.disMissDlg();
                GetWxAppPayParamsResult body = response.body();
                if (body == null||body.getData()==null) {
                    showResultDlg(-3);
                    return;
                }
                DlgUtils.showLoading(VipPayActivity.this, UIUtils.getString(R.string.vip_pay_query_waiting1));
                WXPayParams data = body.getData();
                orderId=data.getOrderNo();
                WxsdkUtil.gotoWxPay(data);
            }
        });

    }
    private String orderId;
    /**
     * 微信支付回调
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(WxPayEvent event) {
        int code = event.getEventId();
        switch (code) {
            case WxPayEvent.GET_WX_PAY_RESULT:
                int resultCode = event.getResultCode();
                if(resultCode==0){
                    //支付成功去查询结果
                    getPayResult();
                }else {
                    showResultDlg(resultCode);
                }

                break;
        }

    }
    private void showResultDlg(int resultCode){
        String result=UIUtils.getString(R.string.vip_pay_fail)+",errCode="+resultCode;
        switch (resultCode) {
            case 0:
                // 支付成功，可跳转到成功页面
                result=UIUtils.getString(R.string.vip_pay_success);
                break;
            case -1:
                // 支付失败
                result=UIUtils.getString(R.string.vip_pay_fail);
                break;
            case -2:
                // 用户取消支付
                result=UIUtils.getString(R.string.vip_pay_cancel);
                break;
            case -3:
                // 请求支付参数失败
                result=UIUtils.getString(R.string.vip_pay_get_params_error);
                break;
        }
        DlgUtils.showDlgNew(this,null,result,
                UIUtils.getString(com.hktf.uilib.R.string.ok),
                null,
                new DlgUtils.MyListener() {
                    @Override
                    public void onConfirm() {
                        if(resultCode==0){
                            finish();
                        }
                    }

                    @Override
                    public void onCancel() {

                    }
                }
        );
    }

    private void getPayResult(){
        showLoadingDlg(getString(R.string.vip_pay_query_waiting));
        DriverEngine.queryWxPayByOrderId(orderId,new BaseCallBackNew<LoginResult>(LoginResult.class){
            @Override
            public void onSUCCESS(Response<LoginResult> response) {
                DlgUtils.disMissDlg();
                LoginResult body = response.body();
                UserDto data = body.getData();
                if (data!=null) {
                    CommUtils.saveUserInfo(data);
                    showResultDlg(0);
                }else {
                    showResultDlg(-1);
                }
            }
        });
    }





    @Override
    protected void onResume() {
        super.onResume();

    }



    @Override
    protected void onPause() {
        super.onPause();

    }


}
